'''
Created on Jul 15, 2009
Demo of SMP feature extraction

@author: xin
@author: Mikael Rousson
'''
import os
import Image
import numpy
import pylab
import datetime

import config
import lp_patch_index

now = datetime.datetime.now

def export_smp_features(patches, fileName):
    f = open(fileName, "w")

    for j in patches.keys():
        tmp= patches[j]
        Length = tmp.shape[0]
        Large = tmp.shape[1]
        f.write(str(Length))
        f.write(' ')
        f.write(str(Large))
        f.write('[')
        for n in range(Large):
            f.write('[')
            for m in range(Length):                
                f.write(str(tmp[m, n]))
                f.write(',')            
            f.write(']')
        f.write(']')
        f.write('#')
    f.close()

def smp_extraction(imName):
    imRgb = Image.open(os.path.join(config.COREL_DATA_DIR, imName))
    im = numpy.array(imRgb, 'f')

    print 'Processing image:', imName, im.shape
    
    # parameters for feature extraction
    ht = 4 # number of decomposition levels
    blur_filt = 'binom5'
    interp_filt = 'binom5'
    dims = numpy.array([[5, 1], [5, 1], [5, 1]])
    diml = numpy.array([[0, 1], [0, 1], [0, 1]])
    lf_dims = 5
    lvlist = numpy.array([1, 2]) # %considered levels

    coeff_ratio = numpy.array([float(1) / float(16), float(1) / float(8)])

    if (lvlist == None):
        kpercent = (1 - coeff_ratio) * 100. * numpy.ones(1, ht)
    else:
        kpercent = (1 - coeff_ratio) * 100. * numpy.ones(len(lvlist))
    
    # index actual image   
    t = now()
    patches = lp_patch_index.lp_patch_index(im, ht, blur_filt, interp_filt,
                                        kpercent, dims, diml, lvlist, lf_dims)    
    print '-processing time:', now() - t 
    
    # save features to file
    export_smp_features(patches, os.path.join(config.OUTPUT_DIR, str(i) 
                                              + '.dat'))

if __name__ == '__main__':
    actual_image = 798
    for i in range(actual_image, 800):
        imName = "% s.jpg" % (i)
        smp_extraction(imName)    
